﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace ZPod.MTG.Windows
{
	public partial class CacheLoaderDialog : Form
	{
		List<Card> _cards;
		private int _loadedCards = 0;
		private object _sync = new object();

		public CacheLoaderDialog(List<Card> cardsToLoad)
		{
			InitializeComponent();
			_cards = new HashSet<Card>(cardsToLoad).ToList();
			progressCachedCards.Maximum = _cards.Count;
		}

		private void CacheLoaderDialog_Shown(object sender, EventArgs e)
		{
			if (MessageBox.Show("¿Desea generar el cache? La operación puede demorar unos minutos", "Generar cache", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				var count = _cards.Count;
				for (int i = 0; i < count; i++)
				{
					var card = _cards[i];

					var loader = new CardLoader() { Card = card, Caller = this };
					ThreadPool.QueueUserWorkItem(loader.LoadCard);
				}
			}
			else
			{
				this.Close();
			}
		}

		private void PerformStep()
		{
			lock (_sync)
			{
				_loadedCards++;
				progressCachedCards.PerformStep();
				labelStatus.Text = String.Format("Cargando {0} de {1}...",
						_loadedCards,
						_cards.Count);

				if (_loadedCards == _cards.Count)
				{
					MessageBox.Show("Cache generado!", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
					this.Close();
				}
			}
		}

		private class CardLoader
		{
			private static object _sync = new object();
			public Card Card;
			public CacheLoaderDialog Caller;

			public void LoadCard(object state)
			{
				lock (_sync)
				{
					CardStorage.GetCardThumbnail(Card);
				}

				Action methodCall = Caller.PerformStep;
				Caller.Invoke(methodCall);
			}

		}
	}
}
